package com.education.wisdom.controller.app;


import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.education.common.pojo.SysUserOther;
import com.education.common.utils.LogUtil;
import com.education.common.utils.UUIDUtils;
import com.education.wisdom.feign.UserFeign;
import com.education.wisdom.pojo.*;
import com.education.wisdom.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

import static com.education.common.core.BaseController.writeJSON;

/**
 * 免费公开课目录体系 信息操作处理
 *
 * @author ruoyi
 * @date 2019-06-13
 */
@Controller
@CrossOrigin
@Slf4j
@ResponseBody
@RequestMapping("/appCatalogFree")
@Api(tags = {"免费公开课"})
public class AppCatalogFreeController {

    @Autowired
    private ICatalogFreeService catalogFreeService;

    @Autowired
    private IMicrolessonService microlessonService;

    @Autowired
    private ICommentOclassService commentOclassService;

    @Autowired
    private ISysAppLoginService loginService;

    @Autowired
    private ICatalogUserLikeService userLikeService;

    @Autowired
    private ILabelService labelService;

    @Autowired
    private ICatalogUserService catalogUserService;

    @Autowired
    private UserFeign userFeign;

    @GetMapping("/list")
    @ApiOperation("查询免费公开课目录")
    public void list(HttpServletResponse response) throws IOException {
        log.info(LogUtil.LogInfo("查询免费公开课目录", new Date()));
        List<CatalogFree> list = catalogFreeService.selectList();
        writeJSON(list, response, "200", "成功");
    }

    @GetMapping("/parent")
    public void parent(HttpServletResponse response, Integer catalogId) throws IOException {
        log.info(LogUtil.LogInfo("查询免费公开课2级目录", new Date()));
        List<CatalogFree> list = catalogFreeService.selectByPatentId(catalogId);
        writeJSON(list, response, "200", "成功");
    }

    /**
     * 实体类进行转换
     */
    public List<MicrolessonCopy> copyBean(List<Microlesson> list) {
        ArrayList<MicrolessonCopy> list1 = Lists.newArrayList();
        for (Microlesson microlesson : list) {
            MicrolessonCopy microlessonCopy = new MicrolessonCopy();
            BeanUtils.copyProperties(microlesson, microlessonCopy);
            list1.add(microlessonCopy);
        }
        return list1;
    }


    @GetMapping("/filter")
    @ApiOperation("目录筛选接口")
    public void filter(HttpServletResponse response, String type, Integer catalogId, Integer pageNo, String oro) throws IOException {
        log.info(LogUtil.LogInfo("目录筛选接口", new Date()));
        int pageSize = 10;
        if (type != null && type.length() > 0) {
            //传的一级目录
            if (type.equals("1")) {
                Map<String, Object> map = new HashMap<>();
                map.put("catalogId", catalogId);
                //最热
                if (oro.equals("1")) {
                    map.put("oro", "1");
                }
                //最新
                if (oro.equals("2")) {
                    map.put("oro", "2");
                }
                PageHelper.startPage(pageNo, pageSize);
                List<Microlesson> microlessonList = microlessonService.selectByMap(map);
                List<MicrolessonCopy> microlessonCopies = copyBean(microlessonList);
                writeJSON(new PageInfo<>(microlessonCopies), response, "200", "成功");
            }
            //传的二级目录
            else if (type.equals("2")) {
                Map<String, Object> map = new HashMap<>();
                map.put("catalogId", catalogId);
                //最热
                if (oro.equals("1")) {
                    map.put("oro", "1");
                }
                //最新
                if (oro.equals("2")) {
                    map.put("oro", "2");
                }
                PageHelper.startPage(pageNo, pageSize);
                List<Microlesson> microlessonList = microlessonService.selectByCatalogId(map);
                List<MicrolessonCopy> microlessonCopies = copyBean(microlessonList);
                writeJSON(new PageInfo<>(microlessonCopies), response, "200", "成功");
            }
        }
        //否则就是type是null 查询全部
        else {
            Map<String, Object> map = new HashMap<>();
            map.put("catalogId", null);
            if (oro != null) {
                //最热
                if (oro.equals("1")) {
                    map.put("oro", "1");
                }
                //最新
                if (oro.equals("2")) {
                    map.put("oro", "2");
                }
            }
            PageHelper.startPage(pageNo, pageSize);
            List<Microlesson> microlessons = microlessonService.selectByCatalogId(map);
            List<MicrolessonCopy> microlessonCopies = copyBean(microlessons);
            writeJSON(new PageInfo<>(microlessonCopies), response, "200", "成功");
        }
    }

    /**
     * 学生APP查看免费公开课详情
     *
     * @param response
     * @param id
     * @param userId
     * @throws IOException
     */
    @PostMapping("/seeDetails")
    @ApiOperation("查看免费公开课详情")
    public void seeDetails(HttpServletResponse response, Integer id, String userId) throws IOException {
        log.info(LogUtil.LogInfo("查看免费公开课详情", new Date()));
        Microlesson microlesson = microlessonService.selectMicrolessonById(id);

        Map<String, Object> map = new HashMap<>();
        map.put("catalogId", microlesson.getId());
        map.put("userId", userId);
        CatalogUserLike catalogUserLike = userLikeService.selectByMap(map);
        if (catalogUserLike == null) {
            microlesson.setIsShouCang("0");
        } else {
            microlesson.setIsShouCang("1");
        }
        writeJSON(microlesson, response, "200", "成功");
        if (microlesson.getRBrowsing() == null) {
            microlesson.setRBrowsing(1);
        } else {
            microlesson.setRBrowsing(microlesson.getRBrowsing() + 1);
        }
        microlessonService.updateMicrolesson(microlesson);

        CatalogUser catalogUser = new CatalogUser();
        catalogUser.setCatalogId(id);
        catalogUser.setUserId(userId);
        List<CatalogUser> catalogUsers = catalogUserService.selectCatalogUserList(catalogUser);
        if (catalogUsers != null && catalogUsers.size() > 0) {
            catalogUsers.get(0).setCreateTime(new Date());
            catalogUserService.updateCatalogUser(catalogUsers.get(0));
        } else {
            catalogUser.setCreateTime(new Date());
            catalogUserService.insertCatalogUser(catalogUser);
        }
    }

    @PostMapping("/addSave")
    @ApiOperation("发布课后评价")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "plText", value = "评论内容", required = true, dataType = "String"),
            @ApiImplicitParam(name = "plCreateuser", value = "发布人", required = true, dataType = "String"),
            @ApiImplicitParam(name = "plCurriculumid", value = "课程编号", required = true, dataType = "String"),
            @ApiImplicitParam(name = "plImage", value = "评论图片", required = true, dataType = "String"),
            @ApiImplicitParam(name = "plAttribute", value = "属性标签编号", required = true, dataType = "String"),
            @ApiImplicitParam(name = "plPraise", value = "1：好评，2：中评，3：差评", required = true, dataType = "String")})
    public void addSave(HttpServletResponse response, CommentOclass commentOclass) throws Exception {
        if (commentOclass.getPlAttribute() != null && !"".equals(commentOclass.getPlAttribute())) {
            log.info(LogUtil.LogInfo("发布课后评价", new Date()));
            commentOclass.setPlId(UUIDUtils.getByUUId());
            commentOclass.setPlCreatetime(new Date());
            commentOclassService.insertCommentOclass(commentOclass);
            writeJSON("添加成功", response, "200", "成功");
        }
        writeJSON("请选择属性标签", response, "201", "请选择属性标签");
    }

    @GetMapping("/allEvaluation")
    @ApiOperation("查询全部评价")
    public void list(HttpServletResponse response, Integer id) throws IOException {
        log.info(LogUtil.LogInfo("查询全部评价", new Date()));
//        int pageSize = 10;
//        PageHelper.startPage(pageNo, pageSize);
        List<CommentOclass> commentOclasses = commentOclassService.selectByCatalogId(id);
//        PageInfo<CommentOclass> info = new PageInfo<>(commentOclasses);
        //好评
        Integer good = 0;
        //中评
        Integer average = 0;
        //差评
        Integer badReview = 0;
        for (CommentOclass commentOclass : commentOclasses) {
            if (commentOclass.getPlPraise().equals("1")) {
                good++;
            } else if (commentOclass.getPlPraise().equals("2")) {
                average++;
            } else if (commentOclass.getPlPraise().equals("3")) {
                badReview++;
            }
            SysUserOther sysUserOther = userFeign.selectOnePCF(commentOclass.getPlCreateuser());
//            SysAppLogin sysAppLogin = loginService.selectSysAppLoginById(commentOclass.getPlCreateuser());
            if (sysUserOther != null) {
                commentOclass.setUserName(sysUserOther.getSysRelname());
            }
        }
        Map<String, Object> map = new HashMap<>();
        map.put("good", good);
        map.put("average", average);
        map.put("badReview", badReview);
        //map.put("info", info);
        writeJSON(map, response, "200", "成功");
    }

    /**
     * 公开课筛选好、中、差评价
     *
     * @param response
     * @param id
     * @param type
     * @param pageNo
     * @throws IOException
     */
    @GetMapping("/screeningEvaluation")
    @ApiOperation("筛选好，中，差评价")
    public void screeningEvaluation(HttpServletResponse response, Integer id, String type, Integer pageNo) throws IOException {
        log.info(LogUtil.LogInfo("筛选好，中，差评价", new Date()));
        int pageSize = 10;
        Map<String, Object> map = new HashMap<>();
        map.put("catalogId", id);
        map.put("type", type);
        PageHelper.startPage(pageNo, pageSize);
        List<CommentOclass> commentOclasses = commentOclassService.selectByType(map);
        for (CommentOclass commentOclass : commentOclasses) {
            //用户信息来自用户表
            SysUserOther sysUserOther = userFeign.selectOnePCF(commentOclass.getPlCreateuser());
            //SysAppLogin sysAppLogin = loginService.selectSysAppLoginById(commentOclass.getPlCreateuser());
            if (sysUserOther != null) {
                commentOclass.setUserName(sysUserOther.getSysRelname());
                commentOclass.setUserIcoUrl(sysUserOther.getSysIco());
            }
            Label label = labelService.selectLabelById(commentOclass.getPlAttribute());
            if (label != null) {
                commentOclass.setLabelName(label.getBqLabel());
            }
        }
        writeJSON(new PageInfo<>(commentOclasses), response, "200", "成功");
    }

    @GetMapping("/labelScreening")
    @ApiOperation("按标签筛选评价")
    public void labelScreening(HttpServletResponse response, Integer id, String labeId, Integer pageSize, Integer pageNum) throws IOException {
        log.info(LogUtil.LogInfo("按标签筛选评价", new Date()));
        Map<String, Object> map = new HashMap<>();
        map.put("catalogId", id);
        map.put("labeId", labeId);
        PageHelper.startPage(pageNum, pageSize);
        List<CommentOclass> commentOclasses = commentOclassService.selectByLabeId(map);
        for (CommentOclass commentOclass : commentOclasses) {
            SysUserOther sysUserOther = userFeign.selectOnePCF(commentOclass.getPlCreateuser());
//            SysAppLogin sysAppLogin = loginService.selectSysAppLoginById(commentOclass.getPlCreateuser());
            if (sysUserOther != null) {
                commentOclass.setUserName(sysUserOther.getSysRelname());
            }
        }
        writeJSON(new PageInfo<>(commentOclasses), response, "200", "成功");
    }

    @PostMapping("/addLikeCatalogs")
    @ApiOperation("用户点小红心收藏该课程")
    public void addLikeCatalogs(HttpServletResponse response, Integer id, String userId) throws Exception {
        log.info(LogUtil.LogInfo("用户新增喜欢的课程", new Date()));
        CatalogUserLike catalogUserLike = new CatalogUserLike();
        catalogUserLike.setUserId(userId);
        catalogUserLike.setCatalogId(id);
        List<CatalogUserLike> catalogUserLikes = userLikeService.selectCatalogUserLikeList(catalogUserLike);
        Map<String, String> map = new HashMap<>();
        if (catalogUserLikes != null && catalogUserLikes.size() > 0) {
            userLikeService.deleteCatalogUserLikeByIds(catalogUserLikes.get(0).getId().toString());
            map.put("status", "0");
        } else {
            catalogUserLike.setCreateTime(new Date());
            userLikeService.insertCatalogUserLike(catalogUserLike);
            map.put("status", "1");
        }
        writeJSON(map, response, "200", "成功");
    }

    @GetMapping("/learn")
    @ApiOperation("我的学习")
    public void learn(HttpServletResponse response, Integer pageSize, Integer pageNum, String userId) throws IOException {
        PageHelper.startPage(pageNum, pageSize);
        List<Microlesson> catalogUsers = microlessonService.selectByUserIdToFreeCatalogId(userId);
        for (Microlesson catalogUser : catalogUsers) {
            catalogUser.setCreateTime(catalogUser.getCr());
        }
        writeJSON(new PageInfo<>(catalogUsers), response, "200", "成功");
    }
}
